<template>
  <div class="change-password-container">
    <a-card title="修改密码" :bordered="false" class="password-card">
      <a-form
        :model="formState"
        name="changePassword"
        :rules="rules"
        @finish="onFinish"
        autocomplete="off"
        layout="vertical"
      >
        <a-form-item
          label="旧密码"
          name="oldPassword"
        >
          <a-input-password
            v-model:value="formState.oldPassword"
            placeholder="请输入旧密码"
          />
        </a-form-item>

        <a-form-item
          label="新密码"
          name="newPassword"
        >
          <a-input-password
            v-model:value="formState.newPassword"
            placeholder="请输入新密码"
          />
        </a-form-item>

        <a-form-item
          label="确认新密码"
          name="confirmPassword"
        >
          <a-input-password
            v-model:value="formState.confirmPassword"
            placeholder="请再次输入新密码"
          />
        </a-form-item>

        <a-form-item>
          <a-button type="primary" html-type="submit" :loading="loading" block>
            确认修改
          </a-button>
        </a-form-item>
      </a-form>
    </a-card>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue';
import { message } from 'ant-design-vue';
import { useRouter } from 'vue-router';
import { useUserStore } from '@/stores/user';
import type { Rule } from 'ant-design-vue/es/form';
import { http } from '@/utils/http';

const router = useRouter();
const userStore = useUserStore();
const loading = ref(false);

interface FormState {
  oldPassword: string;
  newPassword: string;
  confirmPassword: string;
}

const formState = reactive<FormState>({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
});

const validateConfirmPassword = async (_rule: Rule, value: string) => {
  if (!value) {
    return Promise.reject('请确认新密码');
  }
  if (value !== formState.newPassword) {
    return Promise.reject('两次输入的密码不一致');
  }
  return Promise.resolve();
};

const rules = {
  oldPassword: [{ required: true, message: '请输入旧密码' }],
  newPassword: [
    { required: true, message: '请输入新密码' },
    { min: 6, message: '密码长度不能小于6位' }
  ],
  confirmPassword: [{ validator: validateConfirmPassword, trigger: 'change' }]
};

const onFinish = async (values: FormState) => {
  try {
    loading.value = true;
    await http.post('/auth/change-password', {
      oldPassword: values.oldPassword,
      newPassword: values.newPassword
    });
    message.success('密码修改成功，请重新登录');
    userStore.logout();
    router.push('/login');
  } catch (error: any) {
    message.error(error.message || '密码修改失败');
  } finally {
    loading.value = false;
  }
};
</script>

<style scoped>
.change-password-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: calc(100vh - 64px);
  background-color: #f0f2f5;
  padding: 24px;
}

.password-card {
  width: 100%;
  max-width: 400px;
}
</style> 